#!/usr/bin/env ruby
require 'YAML'
require 'fileutils'

PROFILE_PATH = "util/profiles"
version = open("VERSION").read.rstrip

def show_usage
  STDERR.puts "\nusage: ./build [ profile=<name> ] [ --minify ] [ --generate-docs ]"
  STDERR.puts "\nsupported profiles are:"
  Dir.chdir(PROFILE_PATH) do
    STDERR.puts Dir['*.js'].map {|profile| "\t#{profile.sub(/\.js/, '')}"}
  end
  STDERR.puts "\nIf no profile is selected, 'core' will be used\n\n"
  exit(1)
end

# defaults
profile = "core"
minify = false
docs = false
extra = false

ARGV.each do |arg|
  case arg
    when "--minify" then minify = true
    when /^profile=(.*)$/ then profile = $1
    when "--generate-docs" then docs = true
    when /^cat=(.*)$/ then extra = $1
    when "--help" then show_usage
    else
      STDERR.puts("Invalid parameter '#{arg}'") unless arg == "--help"
      show_usage
  end
end
hash = YAML.load_file(File.join(PROFILE_PATH, profile) + ".js")

# clear previous file
target = hash["out"] + "-" + version + ".js"
target_dir = File.dirname(target)

Dir.mkdir(target_dir) unless File.directory?(target_dir)
File.unlink(target) if File.exist?(target)

content = hash["include"].map {|library| File.read(library + ".js") }

File.open(target, "w") {|op| op.puts content }

if extra
  File.open(target, "a") {|op| op.puts File.read(extra)}
end

if minify
  minified_filename = target.sub(/\.js$/, '.min.js')
  `java -jar util/compiler.jar --js=#{ target } \
  --js_output_file=#{ minified_filename }`
end

if docs
  PREFIX    = File.expand_path(File.dirname(__FILE__))
  DOC_DIR   = File.join(PREFIX,    'doc')
  PKG_DIR   = File.join(PREFIX,    'packages')
  SRC_DIR   = File.join(PREFIX,    'src')
  UTIL_DIR  = File.join(PREFIX,    'util')
  HTML_DIR  = File.join(DOC_DIR,   'html')
  EJS_DIR   = File.join(DOC_DIR,   'ejs')
  JODOC_DIR = File.join(PKG_DIR,   'jodoc')
  JODOC_GIT = File.join(JODOC_DIR, '.git')

  JODOC_BIN    = File.join(JODOC_DIR, 'jodoc')
  MARKDOWN_BIN = File.join(UTIL_DIR, 'markdown', 'Markdown.pl')

  def git_jodoc
    if (File.directory?(JODOC_GIT))
      puts "Updating joDoc..."
      `git --git-dir=#{JODOC_GIT} pull -q origin master`
    else
      puts "Cloning joDoc from GitHub..."
      `git clone git://github.com/davebalmer/joDoc.git #{JODOC_DIR}`
    end
  end

  def generate_documentation(output_directory)
    output_directory = File.expand_path(output_directory)
    FileUtils.mkdir_p(output_directory)

    FileUtils.cd(SRC_DIR) do
      files = Dir['**/*.js'].reject{ |f| (f =~ /ie\//) != nil }.join(' ')
      `#{JODOC_BIN} --title "XUI API Reference" --markdown #{MARKDOWN_BIN} --output #{output_directory} #{files}`
    end
  end

  def html_to_ejs(directory)
    FileUtils.cd(directory) do
      rename = Hash.new

      # Generate EJS filenames
      Dir['**/*'].each do |filename|
        # Remove prefix js_
        # Remove prefix _
        # Rename base to basics
        # Remove .html and .js.html
        # Add extension .ejs
        rename[filename] = filename.sub(/^js_/, '') \
                                   .sub(/^_/, '') \
                                   .sub(/base\./, 'basics.') \
                                   .sub(/\..*html/, '') \
                                   .concat('.ejs')
      end

      # Rename each file
      rename.each { |o, n| FileUtils.mv(o, n) }

      # Alter file content
      Dir['**/*'].each do |filename|
        data = File.read(filename)
        # Only save content of <body>
        data.sub!(/.*<body>(.*)<\/body>.*/mi, "\\1")
        # Update links to each filename
        rename.each { |o, n| data.gsub!(o, File.basename(n, '.ejs')) }
        File.open(filename, 'w') { |file| file.write(data) }
      end
    end
  end

  # Prep-work to generate the documentation
  git_jodoc
  FileUtils.rm_r(DOC_DIR) if File.exists?(DOC_DIR)

  # Generate HTML
  generate_documentation(HTML_DIR)

  # Generate EJS
  generate_documentation(EJS_DIR)
  html_to_ejs(EJS_DIR)
  
  puts "Generated documentation at #{DOC_DIR}"
end
